import { readFileSync, writeFileSync } from 'node:fs'
import xlsx from 'node-xlsx'

export function getXlsxData(filename) {
  const xlsxData = xlsx.parse(filename)
  return xlsxData
}

export function xlsxToArray(data, cb) {
  const arr = []

  const keys = data[0]
  data.map((item, index) => {
    if (index == 0) return
    const newItem = {}

    item.map((value, index) => {
      const label = keys[index]
      newItem[label] = value
    })

    if (cb) cb(newItem)
    arr.push(newItem)
  })

  return arr
}

export function saveFile(filename, data) {
  writeFileSync(filename, data)
}

export function getFile(path) {
  return readFileSync(path)
}

export function getJson(path) {
  const data = getFile(path)
  return JSON.parse(data)
}

export function saveJson(filename, data) {
  saveFile(filename, JSON.stringify(data, null, '\t'))
}
